package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.*;
import com.sky.vo.DishVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO){
        Page<Dish> pageInfo = new Page<>(
                dishPageQueryDTO.getPage(),
                dishPageQueryDTO.getPageSize()
        );
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(
                StringUtils.isNotEmpty(dishPageQueryDTO.getName()),
                Dish::getName,
                dishPageQueryDTO.getName()
                );
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        super.page(pageInfo,queryWrapper);
        // VO
        List<DishVO> dishVOList = pageInfo.getRecords().stream().map(item->{
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(item, dishVO);
            // 查询分类名称
            Category category = categoryService.getById(item.getCategoryId());
            if (category!=null){
                dishVO.setCategoryName(category.getName());
            }
            return dishVO;
        }).collect(Collectors.toList());



        PageResult pageResult = new PageResult(
                pageInfo.getTotal(),
                dishVOList
        );
        return pageResult ;
    }

    @Transactional
    @Override
    public void  save(DishDTO dishDTO){
        // 保存基本数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish, "flavors");

        super.save(dish);

        // 创建口味
        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream().map(item->{
            item.setDishId(dish.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavors);
    }

    @Override
    public DishVO getById(Long id){
        DishVO dishVO = new DishVO();
        // 查询菜品
        Dish dish = super.getById(id);
        BeanUtils.copyProperties(dish, dishVO);
        // 查询口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        dishVO.setFlavors(dishFlavorService.list(queryWrapper));
        return dishVO;
    }

    @Override
    public void  updateById(DishDTO dishDTO){
        // 1 删除口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        dishFlavorService.remove(dishFlavorQueryWrapper);

        // 2 更新基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish, "flavors");
        super.updateById(dish);

        // 3 保存新的口味信息
        List<DishFlavor> dishFlavors = dishDTO.getFlavors().stream().map(item->{
            item.setDishId(dish.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavors);

    }


    @Override
    public void  removeByIds(List<Long> ids){
        //  校验
        // 1 是否关联套餐  若关联套餐  不允许删除
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        long count = setmealDishService.count(queryWrapper);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 2 是否 起售   若起售  不允许删除
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(Dish::getId, ids);
        queryWrapper1.eq(Dish::getStatus, 1);
        long count1 = super.count(queryWrapper1);
        if ( count1 > 0 ){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 删除
        // 1 删除基本信息
        super.removeByIds(ids);
        // 1 删除口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.in(DishFlavor::getDishId,  ids);
        dishFlavorService.remove(dishFlavorQueryWrapper);
    }

    @Override
    public void  updateStatus( Integer status, Long id ){
        Dish dish = super.getById(id);
        if (dish!=null){
           dish.setStatus(status);
           super.updateById(dish);
        }
    }


    // 用户

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        List<Dish> dishList = super.list(queryWrapper);

        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, d.getId());
            List<DishFlavor> flavors = dishFlavorService.list(lambdaQueryWrapper);
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }

}
